package top.onedream.buildsmallsoftware.controller


import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import top.onedream.buildsmallsoftware.model.user.User
import top.onedream.buildsmallsoftware.service.UserService
import top.onedream.buildsmallsoftware.util.TokenHolder

/**
 * 用户控制器
 * @author zhangkein
 * @date 2023/05/17
 * @constructor 创建[UserController]
 * @param [userService] 用户服务
 */
@RestController
@RequestMapping("/userInfo")
class UserController(
    private val userService: UserService
) {

    /**
     * 获取当前用户
     * @param [id] id
     * @return [List<User>]
     */
    @GetMapping("/getCurrentUser")
    fun getCurrentUser(
        @RequestParam id: Long?,
        @RequestParam(defaultValue = "0") page: Int,
        @RequestParam(defaultValue = "10") size: Int,
        @RequestParam(defaultValue = "true") desc: Boolean
    ): List<User?> {
        return userService.getCurrentUser(id, page, size, desc)
    }


    /**
     * 让用户通过用户名和年龄
     * @param [username] 用户名
     * @param [age] 年龄
     * @return [User?]
     */
    @Validated
    @GetMapping("/getUserByUsernameAndAge")
    fun getUserByUsernameAndAge(
        @RequestParam   username: String?,
        @RequestParam age: Int?
    ): List<User> {
        return userService.getUserByUsernameAndAge(username, age)
    }


    /**
     * 保存用户
     * @param [user] 用户
     * @return [String?]
     */
    @PostMapping("/saveAUser")
    fun saveAUser(
        @RequestBody user: User
    ): Long {
        return userService.saveAUser(user)
    }

    /**
     * 更新当前用户角色
     * @param [roleId] 角色id
     * @param [roleName] 角色名
     * @return [String?]
     */
    @PutMapping("/updateCurrentUserRole")
    fun updateCurrentUserRole(
        @RequestParam(required = false) roleId: Long?,
        @RequestParam(required = false) roleName: String?
    ): Long? {
        return userService.updateUserRole(roleId, roleName, TokenHolder.user.id!!)
    }


    /**
     * 更新指定用户角色
     * @param [roleId] 角色id
     * @param [roleName] 角色名
     * @return [String?]
     */
    @PutMapping("/updateUserRole")
    fun updateUserRole(
        @RequestParam(required = false) roleId: Long?,
        @RequestParam(required = false) roleName: String?,
        @RequestParam userId: Long
    ): Long? {
        return userService.updateUserRole(roleId, roleName, userId)
    }
}